Deftransform - SBCL
Transforms are something similar to Compiler macros. They are an implementation detail of SBCL implementation of Common Lisp.
For our example, we will implement a very basic transformation on the functions wat and string-wat, which are identical in form to our previous functions gen+ and string+.
Understand there are many more pieces of information and optimisation you can feed the SBCL compiler not covered here. And if anyone more experienced with SBCL internals wants to correct/extent anything regarding my impressions here, please comment and i'll be happy to update my answer:
First we tell the compiler about the existence and type signature of wat. We do this by calling defknown in the sb-c package and inform it that wat takes two parameters of any type: (T T) and that it returns a single value of any type: *
< Collapse code block
(sb-c:defknown wat (T T) *)Then we define a simple transform using sb-c:deftransform, essentially saying when the two parameters fed to wat are strings, we transform the code into a call to string-wat.
< Collapse code block
(sb-c:deftransform wat ((x y) (string string) *) `(string-wat x y))The forms of wat and string-wat for completeness:
< Collapse code block
(defun wat (x y) (if (and (numberp x) (numberp y)) (+ x y) (concatenate 'string x y))) (defun string-wat (x y) (declare (optimize (speed 3) (safety 0)) (string x y)) (concatenate 'string x y "watpow"))And this time a demonstration in SBCL using bound variables but no explicit type declarations:
< Collapse code block
(let ((a (concatenate 'string "bo" "b")) (b (concatenate 'string "dole"))) (wat a b))And the returned string should be "bobdolewatpow".
Anoter useful comment was:
AFAIK reading the SBCL sources is the only way to learn how deftransform works. But before diving into SBCL sources checkout Paul Khuong's Starting to Hack on SBCL or at the very least The Python Compiler for CMU Common Lisp it links to to have an overview of how SBCL works.
References
- https://stackoverflow.com/questions/44342104/using-deftransform-defknown-in-sbcl-internals-to-get-the-compiler-to-transform-u
- https://pvk.ca/Blog/2013/04/13/starting-to-hack-on-sbcl/ (Deftransform - SBCL)
- http://www.cs.cmu.edu/~ram/pub/lfp.ps (Deftransform - SBCL)